import os
import sys
from PIL import Image
import pytesseract
import cv2
import numpy as np
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QFileDialog, QTextEdit, QHBoxLayout, QDialog, QSlider
from PyQt5.QtGui import QPixmap, QFont, QIcon, QPainter, QColor
from PyQt5.QtCore import Qt, QSize
import re

# Tesseract يولىنى ۋە TESSDATA_PREFIX نى بەلگىلەش
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
os.environ['TESSDATA_PREFIX'] = r'C:\Program Files\Tesseract-OCR\tessdata'

def preprocess_image(image_path):
    img = cv2.imread(image_path)
    img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
    gray = clahe.apply(gray)
    thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
    opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
    return opening

def clean_text(text):
    lines = [' '.join(line.split()) for line in text.split('\n') if line.strip()]
    text = ' '.join(lines)
    text = re.sub(r'(?<=\S)(?=[،.؟!])', ' ', text)
    text = re.sub(r'\s+', ' ', text)
    return text.strip()

def tesseract_ocr(image_path):
    try:
        preprocessed_img = preprocess_image(image_path)
        custom_config = r'--oem 1 --psm 6 -c preserve_interword_spaces=1 -c segment_penalty_dict=1 -c segment_penalty_garbage=1'
        text = pytesseract.image_to_string(preprocessed_img, lang='uig', config=custom_config)
        return clean_text(text)
    except FileNotFoundError:
        return f"خاتالىق: '{image_path}' دېگەن ھۆججەت تېپىلمىدى."
    except Exception as e:
        return f"خاتالىق يۈز بەردى: {str(e)}"

class ImagePreprocessDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("رەسىم تەڭشەش")
        self.setLayout(QVBoxLayout())

        self.brightness_slider = QSlider(Qt.Horizontal)
        self.brightness_slider.setRange(-100, 100)
        self.brightness_slider.setValue(0)
        self.brightness_slider.valueChanged.connect(self.update_image)

        self.contrast_slider = QSlider(Qt.Horizontal)
        self.contrast_slider.setRange(-100, 100)
        self.contrast_slider.setValue(0)
        self.contrast_slider.valueChanged.connect(self.update_image)

        self.layout().addWidget(QLabel("يورۇقلۇق:"))
        self.layout().addWidget(self.brightness_slider)
        self.layout().addWidget(QLabel("كونتراست:"))
        self.layout().addWidget(self.contrast_slider)

        button_layout = QHBoxLayout()
        ok_button = QPushButton("جەزملەشتۈرۈش")
        ok_button.clicked.connect(self.accept)
        cancel_button = QPushButton("ئەمەلدىن قالدۇرۇش")
        cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(ok_button)
        button_layout.addWidget(cancel_button)
        self.layout().addLayout(button_layout)

    def update_image(self):
        # رەسىمنى يېڭىلاش كودى
        pass

class UyghurOCRApp(QWidget):
    def __init__(self):
        super().__init__()
        self.image_path = None
        self.initUI()

    def initUI(self):
        self.setWindowTitle('ئۇيغۇرچە OCR پروگراممىسى')
        self.resize(1000, 700)
        self.setStyleSheet("""
            QWidget {
                background-color: #f5f5f5;
                font-family:'UKIJ CJK', sans-serif;
            }
            QPushButton {
                background-color: #3498db;
                color: white;
                border: none;
                padding: 10px 20px;
                text-align: center;
                text-decoration: none;
                font-size: 16px;
                margin: 4px 2px;
                border-radius: 5px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QTextEdit {
                background-color: white;
                border: 1px solid #bdc3c7;
                border-radius: 5px;
                padding: 10px;
                font-size: 16px;
            }
        """)

        main_layout = QHBoxLayout()
        left_layout = QVBoxLayout()
        right_layout = QVBoxLayout()

        self.image_label = QLabel(self)
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setMinimumSize(500, 400)
        self.image_label.setStyleSheet("""
            QLabel {
                background-color: white;
                border: 2px dashed #bdc3c7;
                border-radius: 10px;
            }
        """)
        left_layout.addWidget(self.image_label)

        button_layout = QHBoxLayout()
        for button_text, callback, icon_path in [
            ('رەسىم تاللاش', self.select_image, 'icons/image.png'),
            ('تونۇش', self.perform_ocr, 'icons/ocr.png')
        ]:
            button = QPushButton(button_text, self)
            button.clicked.connect(callback)
            button.setFont(QFont('UKIJ CJK', 14))
            button.setIcon(QIcon(icon_path))
            button.setIconSize(QSize(24, 24))
            button_layout.addWidget(button)
        left_layout.addLayout(button_layout)

        self.result_text = QTextEdit(self)
        self.result_text.setReadOnly(True)
        self.result_text.setFont(QFont('UKIJ CJK', 16))
        self.result_text.setStyleSheet("""
            QTextEdit {
                background-color: #ecf0f1;
                border: 1px solid #bdc3c7;
                border-radius: 10px;
                padding: 15px;
            }
        """)
        right_layout.addWidget(QLabel("تونۇش نەتىجىسى:"))
        right_layout.addWidget(self.result_text)

        main_layout.addLayout(left_layout, 1)
        main_layout.addLayout(right_layout, 1)
        self.setLayout(main_layout)

    def select_image(self):
        self.image_path, _ = QFileDialog.getOpenFileName(self, 'رەسىم تاللاش', '', 'رەسىم ھۆججەتلىرى (*.png *.jpg *.bmp)')
        if self.image_path:
            self.original_image = cv2.imread(self.image_path)
            self.show_image()

    def show_image(self):
        pixmap = QPixmap(self.image_path)
        self.image_label.setPixmap(pixmap.scaled(500, 400, Qt.KeepAspectRatio, Qt.SmoothTransformation))

    def perform_ocr(self):
        if self.image_path:
            try:
                self.result_text.setText("تونۇۋاتىدۇ...")
                QApplication.processEvents()
                result = tesseract_ocr(self.image_path)
                self.result_text.setText(result)
            except Exception as e:
                error_message = f"خاتالىق يۈز بەردى: {str(e)}"
                self.result_text.setText(error_message)
                print(error_message)
        else:
            self.result_text.setText('ئاۋۋال رەسىم تاللاڭ')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = UyghurOCRApp()
    ex.show()
    sys.exit(app.exec_())
